package team.nine.kuaichezuche.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import team.nine.kuaichezuche.model.RentalOrder;
import team.nine.kuaichezuche.model.VehicleInstance;
import team.nine.kuaichezuche.repository.RentalOrderRepository;
import team.nine.kuaichezuche.repository.VehicleInstanceRepository;
import team.nine.kuaichezuche.service.RentalOrderService;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 租车订单服务实现类
 */
@Service
public class RentalOrderServiceImpl implements RentalOrderService {
    
    @Autowired
    private RentalOrderRepository rentalOrderRepository;
    
    @Autowired
    private VehicleInstanceRepository vehicleInstanceRepository;
    
    /**
     * 创建租车订单
     */
    @Override
    @Transactional
    public RentalOrder createOrder(Integer vehicleId, Long renterId, Date startTime, Date endTime, Double totalPrice) {
        // 验证参数
        if (vehicleId == null || renterId == null || startTime == null || endTime == null || totalPrice == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 检查车辆是否存在
        Optional<VehicleInstance> vehicleInstanceOptional = vehicleInstanceRepository.findById(vehicleId);
        if (!vehicleInstanceOptional.isPresent()) {
            throw new IllegalArgumentException("车辆不存在");
        }
        
        // 检查车辆状态是否为可租用（0）
        VehicleInstance vehicleInstance = vehicleInstanceOptional.get();
        if (vehicleInstance.getStatus() != 0) {
            throw new IllegalArgumentException("车辆当前不可租用");
        }
        
        // 创建订单对象
        RentalOrder order = new RentalOrder();
        order.setVehicleId(vehicleId);
        order.setRenterId(renterId);
        order.setStartTime(startTime);
        order.setEndTime(endTime);
        order.setTotalPrice(BigDecimal.valueOf(totalPrice));
        order.setStatus((byte) 0); // 设置为待支付状态
        
        // 保存订单
        return rentalOrderRepository.save(order);
    }
    
    /**
     * 根据订单ID查询订单
     */
    @Override
    public RentalOrder getOrderById(Integer orderId) {
        if (orderId == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        
        return rentalOrderRepository.findById(orderId).orElse(null);
    }
    
    /**
     * 根据用户ID查询订单
     */
    @Override
    public List<RentalOrder> getOrdersByRenterId(Long renterId) {
        if (renterId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        
        return rentalOrderRepository.findByRenterId(renterId);
    }
    
    /**
     * 根据车辆实例ID查询订单
     */
    @Override
    public List<RentalOrder> getOrdersByVehicleId(Integer vehicleId) {
        if (vehicleId == null) {
            throw new IllegalArgumentException("车辆ID不能为空");
        }
        
        return rentalOrderRepository.findByVehicleId(vehicleId);
    }
    
    /**
     * 更新订单状态
     */
    @Override
    @Transactional
    public RentalOrder updateOrderStatus(Integer orderId, Byte status) {
        if (orderId == null || status == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 检查订单是否存在
        Optional<RentalOrder> orderOptional = rentalOrderRepository.findById(orderId);
        if (!orderOptional.isPresent()) {
            throw new IllegalArgumentException("订单不存在");
        }
        
        // 更新订单状态
        RentalOrder order = orderOptional.get();
        order.setStatus(status);
        
        return rentalOrderRepository.save(order);
    }
    
    /**
     * 支付订单
     */
    @Override
    @Transactional
    public RentalOrder payOrder(Integer orderId) {
        // 检查订单是否可以支付
        if (!isOrderPayable(orderId)) {
            throw new IllegalArgumentException("订单已过期或不可支付");
        }
        
        // 更新订单状态为已支付
        RentalOrder order = updateOrderStatus(orderId, (byte) 1);
        
        // 更新车辆状态为已租出并增加租用次数
        Optional<VehicleInstance> vehicleInstanceOptional = vehicleInstanceRepository.findById(order.getVehicleId());
        if (vehicleInstanceOptional.isPresent()) {
            VehicleInstance vehicleInstance = vehicleInstanceOptional.get();
            vehicleInstance.setStatus((byte) 1); // 设置为已租出状态
            // 增加租用次数，处理可能的null值
            Integer currentRentalCount = vehicleInstance.getRentalCount();
            vehicleInstance.setRentalCount(currentRentalCount != null ? currentRentalCount + 1 : 1);
            vehicleInstanceRepository.save(vehicleInstance);
        }
        
        return order;
    }
    
    /**
     * 取消订单
     */
    @Override
    @Transactional
    public RentalOrder cancelOrder(Integer orderId) {
        // 检查订单是否存在
        Optional<RentalOrder> orderOptional = rentalOrderRepository.findById(orderId);
        if (!orderOptional.isPresent()) {
            throw new IllegalArgumentException("订单不存在");
        }
        
        // 检查订单状态是否为待支付
        RentalOrder order = orderOptional.get();
        if (order.getStatus() != 0) {
            throw new IllegalArgumentException("只能取消待支付状态的订单");
        }
        
        // 更新订单状态为已取消
        order.setStatus((byte) 3);
        
        return rentalOrderRepository.save(order);
    }
    
    /**
     * 检查订单是否可以被支付（未过期且状态为待支付）
     */
    @Override
    public boolean isOrderPayable(Integer orderId) {
        // 检查订单是否存在
        Optional<RentalOrder> orderOptional = rentalOrderRepository.findById(orderId);
        if (!orderOptional.isPresent()) {
            return false;
        }
        
        RentalOrder order = orderOptional.get();
        // 检查订单状态是否为待支付
        if (order.getStatus() != 0) {
            return false;
        }
        
        // 检查订单是否在5分钟内
        long now = System.currentTimeMillis();
        long orderCreatedTime = order.getCreatedAt().getTime();
        long fiveMinutes = 5 * 60 * 1000;
        
        return now - orderCreatedTime <= fiveMinutes;
    }
    
    /**
     * 定期检查并处理超时订单
     * 每1分钟执行一次
     */
    @Scheduled(fixedRate = 60000)
    @Transactional
    public void processExpiredOrders() {
        // 查询所有状态为待支付的订单
        List<RentalOrder> pendingOrders = rentalOrderRepository.findAll().stream()
                .filter(order -> order.getStatus() == 0)
                .collect(java.util.stream.Collectors.toList());
        
        long now = System.currentTimeMillis();
        long fiveMinutes = 5 * 60 * 1000;
        
        // 处理超时订单
        for (RentalOrder order : pendingOrders) {
            long orderCreatedTime = order.getCreatedAt().getTime();
            if (now - orderCreatedTime > fiveMinutes) {
                // 设置订单状态为已取消
                order.setStatus((byte) 3);
                rentalOrderRepository.save(order);
            }
        }
    }
}